<template>
  <div class="search">
    <div class="sear-box">
      <input v-model="keyword" type="text" class="search-input" placeholder="输出城市名或拼音">
    </div>
    <div class="search-content" ref="search" v-show="keyword">
      <ul>
        <li @click="handleCityClick(city.name)" class="search-item border-bottom" v-for="city in list" :key="city.id">{{city.name}}</li>
        <li class="search-item border-bottom no-data" v-show="noData">没有匹配数据</li>
      </ul>
    </div>
  </div>
</template>
<script>
import Bscroll from 'better-scroll'

export default {
  name: 'CitySearch',
  data () {
    return {
      keyword:'',
      list:[],
      timer:null
    }
  },
  props: {
    cities:Object
  },
  computed: {
    noData () {
      return !this.list.length
    }
  },
  watch: {
    keyword () {
      if(this.timer) {
        clearTimeout(this.timer)
      }
      if(!this.keyword) {
        this.list = []
        return
      }
      this.timer = setTimeout(() => {
        const result = []
        for (let i in this.cities) {
          this.cities[i].forEach((val) => {
            if(val.spell.indexOf(this.keyword) > -1 || val.name.indexOf(this.keyword) > -1) {
              result.push(val)
            }
          })
        }
        this.list = result
      }, 100);
    }
  },
  methods: {
    handleCityClick (city) {
      this.$store.commit('changeCity',city)
      this.$router.push('/')
    }
  },
  mounted () {
    this.scroll = new Bscroll(this.$refs.search)
  }
}
</script>
<style lang="scss" scoped>
@import '~styles/varibles.scss';
.search{
  height: .72rem;
  background-color: $baseColor;
  padding: 0 .1rem;
  .search-input{
    height: .62rem;
    line-break: .62rem;
    width: 100%;
    text-align: center;
    border-radius: .06rem;
    color: $baseFontColor;
    padding: 0 .1rem;
    box-sizing: border-box;
  }
  .search-content{
    position: absolute;
    z-index: 1;
    overflow: hidden;
    top: 1.58rem;
    left: 0;
    right: 0;
    bottom: 0;
    background: #eee;
    .search-item{
      line-height: .62rem;
      padding: 0 .2rem;
      color: #666;
      background-color: #fff;
    }
    .no-data{
      text-align: center;
    }
  }
}
</style>

